package com.hlf.robot.utils;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class OkHttpResponse implements Serializable {
    private int code;
    private Headers headers;
    private boolean successful;
    private boolean redirect;
    private String contentType;
    private long length;
    private byte[] body;
    private Integer statusCode;
    private Charset charset;

    public static OkHttpResponse read(Response response) throws IOException {
        return new OkHttpResponse(response);
    }

    public OkHttpResponse(Response response) throws IOException {
        this.code = response.code();
        this.headers = response.headers();
        this.successful = response.isSuccessful();
        this.redirect = response.isRedirect();
        ResponseBody body = response.body();
        if (body != null) {
            MediaType mediaType = body.contentType();
            if (mediaType != null) {
                this.contentType = mediaType.toString();
                this.charset = mediaType.charset();
            }
            this.length = body.contentLength();
            this.body = body.bytes();
        } else {
            this.length = 0;
            this.body = new byte[0];
        }

        if (this.charset == null) {
            this.charset = StandardCharsets.UTF_8;
        }
        this.statusCode = response.code();

        response.close();
    }


    public boolean isSuccessful() {
        return this.code == 200;
    }


    public String getBody() {
        return new String(this.body, this.charset);
    }


    public byte[] getByte() {
        return this.body;
    }


    public int statusCode() {
        return this.statusCode;
    }


    public String getContentType() {
        return this.contentType;
    }


    public long getContentLength() {
        return this.length;
    }


    public Charset getCharset() {
        return this.charset;
    }


    public String getHeader(String headerName) {
        return this.headers.get(headerName);
    }

}
